package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

// http
func main() {
	//server()
	jsonStudy()
}

func client() {
	client := http.Client{}
	resp, err := client.Get("https://www.baidu.com")
	if err != nil {
		fmt.Println("response error", resp)
	}
	fmt.Println("response,", resp)

	buffer := make([]byte, 1024)

	_, err = resp.Body.Read(buffer)

	if err != nil {
		fmt.Println("response get body error", err)
	}

	fmt.Println("read content", string(buffer))

	fmt.Println("get url", resp.Request.URL)
}

func server() {
	//这个得放在上面，因为下面的Listen死循环了，不会再往下走了
	http.HandleFunc("/getUser", func(writer http.ResponseWriter, request *http.Request) {
		fmt.Println("hello world")
		response := "hello world"

		write, err := writer.Write([]byte(response))

		if err != nil {
			fmt.Println("response error")
		}

		fmt.Println(write)
	})
	//死循环
	if err := http.ListenAndServe("127.0.0.1:9090", nil); err != nil {
		fmt.Println("handler request error", err)
		return
	}

}

type student struct {
	Name string `json:"name"` //结构体标签，这样序列化出来的字段就是name

	Code string `json:"code"`

	Age string `json:"-"` //在json中不编码

	gender string //首字母小写得字段不能序列化
}

func jsonStudy() {
	zs := student{
		Name:   "zs",
		Code:   "1",
		Age:    "1",
		gender: "男",
	}

	marshal, err := json.Marshal(zs) //只读zs，返回新值则值传递

	if err != nil {
		fmt.Println("json convert error", err)
	}
	fmt.Println("json string", string(marshal)) //问题在于小写的gender没有生成

	var ls student

	//反序列化string为结构体
	err = json.Unmarshal(marshal, &ls) //修改ls，所以传指针

	fmt.Println(ls)
}

func mapStudy() {
	mapData := make(map[int]string, 10)
	mapData[0] = "hello world"
	length := len(mapData)
	fmt.Println("map length", length)
	for key, value := range mapData {
		fmt.Println("map key", key)
		fmt.Println("map value", value)
	}
}
